using MauiBuilder.Models;
using Microsoft.Extensions.Logging;

namespace MauiBuilder.Services;

/// <summary>
/// 支付管理服务实现
/// </summary>
public class PaymentManagerService : IPaymentManagerService
{
    private readonly Dictionary<PaymentType, IPaymentService> _paymentServices;
    private readonly ILogger<PaymentManagerService> _logger;
    private readonly IServiceProvider _serviceProvider;

    public PaymentManagerService(ILogger<PaymentManagerService> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _paymentServices = new Dictionary<PaymentType, IPaymentService>();
        
        InitializePaymentServices();
    }

    /// <summary>
    /// 初始化支付服务
    /// </summary>
    private void InitializePaymentServices()
    {
        try
        {
            // 注册支付宝服务
            var alipayService = _serviceProvider.GetService<IAlipayService>();
            if (alipayService != null)
            {
                RegisterPaymentService(PaymentType.Alipay, alipayService);
                _logger.LogInformation("支付宝服务注册成功");
            }

            // 注册微信支付服务
            var wechatPayService = _serviceProvider.GetService<IWeChatPayService>();
            if (wechatPayService != null)
            {
                RegisterPaymentService(PaymentType.WeChatPay, wechatPayService);
                _logger.LogInformation("微信支付服务注册成功");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化支付服务失败");
        }
    }

    /// <summary>
    /// 获取支付服务
    /// </summary>
    public IPaymentService GetPaymentService(PaymentType paymentType)
    {
        if (_paymentServices.TryGetValue(paymentType, out var service))
        {
            return service;
        }

        throw new NotSupportedException($"不支持的支付类型: {paymentType}");
    }

    /// <summary>
    /// 注册支付服务
    /// </summary>
    public void RegisterPaymentService(PaymentType paymentType, IPaymentService service)
    {
        if (service == null)
            throw new ArgumentNullException(nameof(service));

        _paymentServices[paymentType] = service;
        _logger.LogInformation("支付服务注册成功: {PaymentType}", paymentType);
    }

    /// <summary>
    /// 获取支持的支付类型
    /// </summary>
    public IEnumerable<PaymentType> GetSupportedPaymentTypes()
    {
        return _paymentServices.Keys.Where(type =>
        {
            var service = _paymentServices[type];
            return service.IsSupportedPlatform;
        });
    }

    /// <summary>
    /// 统一支付接口
    /// </summary>
    public async Task<PaymentResponse> PayAsync(PaymentRequest request)
    {
        try
        {
            if (request == null)
                throw new ArgumentNullException(nameof(request));

            _logger.LogInformation("开始处理支付请求，订单号: {OrderId}, 支付类型: {PaymentType}", 
                request.OrderId, request.PaymentType);

            var service = GetPaymentService(request.PaymentType);
            
            if (!service.IsSupportedPlatform)
            {
                return new PaymentResponse
                {
                    IsSuccess = false,
                    OrderId = request.OrderId,
                    Status = PaymentStatus.Failed,
                    ErrorMessage = $"当前平台不支持{request.PaymentType}支付",
                    ErrorCode = "PLATFORM_NOT_SUPPORTED"
                };
            }

            var response = await service.CreatePaymentAsync(request);
            
            _logger.LogInformation("支付请求处理完成，订单号: {OrderId}, 结果: {IsSuccess}", 
                request.OrderId, response.IsSuccess);

            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理支付请求失败，订单号: {OrderId}", request?.OrderId);
            return new PaymentResponse
            {
                IsSuccess = false,
                OrderId = request?.OrderId ?? "",
                Status = PaymentStatus.Failed,
                ErrorMessage = ex.Message,
                ErrorCode = "PAYMENT_FAILED"
            };
        }
    }

    /// <summary>
    /// 统一查询接口
    /// </summary>
    public async Task<PaymentResult> QueryAsync(string orderId, PaymentType paymentType)
    {
        try
        {
            if (string.IsNullOrEmpty(orderId))
                throw new ArgumentException("订单号不能为空", nameof(orderId));

            _logger.LogInformation("开始查询支付结果，订单号: {OrderId}, 支付类型: {PaymentType}", 
                orderId, paymentType);

            var service = GetPaymentService(paymentType);
            var result = await service.QueryPaymentAsync(orderId);

            _logger.LogInformation("支付结果查询完成，订单号: {OrderId}, 状态: {Status}", 
                orderId, result.Status);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询支付结果失败，订单号: {OrderId}", orderId);
            return new PaymentResult
            {
                IsSuccess = false,
                OrderId = orderId,
                Status = PaymentStatus.Failed,
                Message = ex.Message
            };
        }
    }

    /// <summary>
    /// 取消支付
    /// </summary>
    public async Task<bool> CancelPaymentAsync(string orderId, PaymentType paymentType)
    {
        try
        {
            if (string.IsNullOrEmpty(orderId))
                throw new ArgumentException("订单号不能为空", nameof(orderId));

            _logger.LogInformation("开始取消支付，订单号: {OrderId}, 支付类型: {PaymentType}", 
                orderId, paymentType);

            var service = GetPaymentService(paymentType);
            var result = await service.CancelPaymentAsync(orderId);

            _logger.LogInformation("取消支付完成，订单号: {OrderId}, 结果: {Result}", 
                orderId, result);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "取消支付失败，订单号: {OrderId}", orderId);
            return false;
        }
    }

    /// <summary>
    /// 初始化支付管理服务
    /// </summary>
    public async Task InitializeAsync(PaymentConfig config)
    {
        try
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            _logger.LogInformation("开始初始化支付管理服务");

            // 初始化所有已注册的支付服务
            var initializeTasks = _paymentServices.Values.Select(service => service.InitializeAsync(config));
            await Task.WhenAll(initializeTasks);

            _logger.LogInformation("支付管理服务初始化完成");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化支付管理服务失败");
            throw;
        }
    }

    /// <summary>
    /// 检查支付是否可用
    /// </summary>
    public async Task<bool> IsPaymentAvailableAsync(PaymentType paymentType)
    {
        try
        {
            if (!_paymentServices.TryGetValue(paymentType, out var service))
            {
                _logger.LogWarning("未找到支付服务: {PaymentType}", paymentType);
                return false;
            }

            // 检查平台支持
            if (!service.IsSupportedPlatform)
            {
                _logger.LogInformation("当前平台不支持支付类型: {PaymentType}", paymentType);
                return false;
            }

            // 对于微信支付，额外检查微信是否安装
            if (paymentType == PaymentType.WeChatPay && service is IWeChatPayService wechatService)
            {
                var isInstalled = await wechatService.IsWeChatInstalledAsync();
                if (!isInstalled)
                {
                    _logger.LogInformation("微信未安装，无法使用微信支付");
                    return false;
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "检查支付可用性失败，支付类型: {PaymentType}", paymentType);
            return false;
        }
    }

    /// <summary>
    /// 验证支付回调
    /// </summary>
    public async Task<PaymentResult> VerifyCallbackAsync(PaymentType paymentType, Dictionary<string, string> callbackData)
    {
        try
        {
            if (callbackData == null || !callbackData.Any())
                throw new ArgumentException("回调数据不能为空", nameof(callbackData));

            _logger.LogInformation("开始验证支付回调，支付类型: {PaymentType}", paymentType);

            var service = GetPaymentService(paymentType);
            var result = await service.VerifyCallbackAsync(callbackData);

            _logger.LogInformation("支付回调验证完成，订单号: {OrderId}, 结果: {IsSuccess}", 
                result.OrderId, result.IsSuccess);

            return result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "验证支付回调失败，支付类型: {PaymentType}", paymentType);
            return new PaymentResult
            {
                IsSuccess = false,
                Status = PaymentStatus.Failed,
                Message = ex.Message
            };
        }
    }

    /// <summary>
    /// 初始化支付配置
    /// </summary>
    public async Task InitializePaymentConfigAsync(PaymentType paymentType, PaymentConfig config)
    {
        try
        {
            if (config == null)
                throw new ArgumentNullException(nameof(config));

            _logger.LogInformation("初始化支付配置，支付类型: {PaymentType}", paymentType);

            var service = GetPaymentService(paymentType);
            await service.InitializeAsync(config);

            _logger.LogInformation("支付配置初始化完成，支付类型: {PaymentType}", paymentType);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "初始化支付配置失败，支付类型: {PaymentType}", paymentType);
            throw;
        }
    }

    /// <summary>
    /// 获取支付服务状态
    /// </summary>
    public Dictionary<PaymentType, bool> GetPaymentServiceStatus()
    {
        var status = new Dictionary<PaymentType, bool>();

        foreach (var kvp in _paymentServices)
        {
            status[kvp.Key] = kvp.Value.IsSupportedPlatform;
        }

        return status;
    }

    /// <summary>
    /// 检查支付类型是否可用
    /// </summary>
    public bool IsPaymentTypeAvailable(PaymentType paymentType)
    {
        if (!_paymentServices.TryGetValue(paymentType, out var service))
            return false;

        return service.IsSupportedPlatform;
    }

    /// <summary>
    /// 获取推荐的支付类型
    /// </summary>
    public PaymentType? GetRecommendedPaymentType()
    {
        var supportedTypes = GetSupportedPaymentTypes().ToList();
        
        if (!supportedTypes.Any())
            return null;

        // 根据平台推荐支付方式
        if (DeviceInfo.Current.Platform == DevicePlatform.Android)
        {
            // Android平台优先推荐支付宝
            if (supportedTypes.Contains(PaymentType.Alipay))
                return PaymentType.Alipay;
            
            if (supportedTypes.Contains(PaymentType.WeChatPay))
                return PaymentType.WeChatPay;
        }
        else if (DeviceInfo.Current.Platform == DevicePlatform.iOS)
        {
            // iOS平台优先推荐微信支付
            if (supportedTypes.Contains(PaymentType.WeChatPay))
                return PaymentType.WeChatPay;
            
            if (supportedTypes.Contains(PaymentType.Alipay))
                return PaymentType.Alipay;
        }

        return supportedTypes.First();
    }
}